/******************************************************************************
 * @File name   :      PackageImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 22, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 22, 2015 11:45:40 AM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.purchase.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.coupon.constants.CouponConstants;
import com.cap.bts.crmdp.dealer.coupon.dao.ITicketLineDefineDao;
import com.cap.bts.crmdp.dealer.coupon.dao.ITicketPriceOfDealerDao;
import com.cap.bts.crmdp.dealer.coupon.domain.TicketPriceOfDealer;
import com.cap.bts.crmdp.dealer.masterdata.dao.IMaintainDealerDao;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.meal.dao.IPackageEligibilityDao;
import com.cap.bts.crmdp.dealer.meal.domain.PackageDealerSelected;
import com.cap.bts.crmdp.dealer.meal.domain.PackageEligibilityModel;
import com.cap.bts.crmdp.dealer.meal.service.IMealManageService;
import com.cap.bts.crmdp.dealer.purchase.dao.IPackageDefinitionDao;
import com.cap.bts.crmdp.dealer.purchase.domain.PackageDefinition;
import com.cap.bts.crmdp.dealer.purchase.dto.PackageDefinitionResultsDto;
import com.cap.bts.crmdp.dealer.purchase.dto.PackageDefinitionResultsForSelectDto;
import com.cap.bts.crmdp.dealer.purchase.service.IPackageDefinitionService;
import com.cap.bts.framework.codemapping.dao.ICodeMappingDao;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class PackageDefinitionSerivceImpl extends BaseServiceImpl implements IPackageDefinitionService{
   @Resource(name = "packageDefinitionDao")
   
   private IPackageDefinitionDao packageDefinitionDao;
   
   @Autowired
   IMealManageService mealManageService;
   @Autowired
   ITicketLineDefineDao iTicketLineDefineDao;
   @Autowired
   ITicketPriceOfDealerDao ticketPriceOfDealerDao;
   @Autowired
   IPackageEligibilityDao packageEligibilityDao;
   @Autowired
   ICodeMappingDao codeMappingDao;
   @Autowired
   IMaintainDealerDao dealerDao;
   
   @SuppressWarnings("rawtypes")
public List<PackageDefinitionResultsDto> getAllPackageDefinitionList() throws AppException{
       
       List<PackageDefinitionResultsDto> packageDefinitionResultsDtolist= new ArrayList<PackageDefinitionResultsDto>();
       //获取当前门店信息
       MasterDataDealerInfo dealerInfo = dealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
       //获取套餐
       List<PackageDefinition> list=packageDefinitionDao.getAllPackageDefinitionList();
       PackageDefinitionResultsDto dto=new PackageDefinitionResultsDto();
       //默认套餐为空设置
       dto.setId(Long.valueOf("-1"));
       dto.setName(null);
       dto.setPrice(null);
       dto.setIsPhysicalCard(0);
       packageDefinitionResultsDtolist.add(dto);
       for(int i=0;i<list.size();i++){
    	   //查看套餐的适用范围,适用范围外的要删掉
    	   
    	   //构造优先级的map
           Map<String,String> priority = new HashMap<String,String>();
           List<CodeInfo> priorityList = codeMappingDao.getCodeInfoByCodeType(CouponConstants.DEALERPROPERTY);
           if(priorityList != null && !priorityList.isEmpty()){
               for(int k=0; k<priorityList.size(); k++){
                   priority.put(priorityList.get(k).getCode().substring(2), priorityList.get(k).getCode());
               }
           }
           
           if(priority != null && !priority.isEmpty()){
        	   List<PackageEligibilityModel> packageEligibilityList = packageEligibilityDao.getPackageEligibilityByPackageDefId(list.get(i).getId());
        	   if(packageEligibilityList != null && !packageEligibilityList.isEmpty()){
        		   boolean isExist = false;
        		   for(int j=0; j<packageEligibilityList.size(); j++){
        			   if(priorityList != null && !priorityList.isEmpty()){
        	               for(int k=0; k<priorityList.size(); k++){
        	            	   if(priorityList.get(k).getCode().equals(packageEligibilityList.get(j).getDealerProperty())){
        	            		   String property = packageEligibilityList.get(j).getDealerProperty().substring(2);
                				   if(packageEligibilityList.get(j).getPropertyValue().equals(dealerDao.getDealersByProperty(property,dealerInfo.getDealerNum()))){
                					   isExist = true;
                				   }
                			   }
        	               }
        	           }
        			   
        		   }
        		   if(!isExist){
        			   list.remove(i);
					   i--;
					   continue;
        		   }
        	   }
           }
           //查找地方性价格
           Double price = null;
           List<TicketPriceOfDealer> ticketPriceOfDealerList = ticketPriceOfDealerDao.getTicketPriceOfDealerByDealerAndPackageDefId(UserUtil.getCurrentUser().getDealerId(),
               list.get(i).getId());
           if(ticketPriceOfDealerList != null && !ticketPriceOfDealerList.isEmpty()){
               price = ticketPriceOfDealerList.get(0).getPrice();
           }else{
               price = list.get(i).getPrice();
           }
           dto=new PackageDefinitionResultsDto();
           dto.setId(list.get(i).getId());
           dto.setName(list.get(i).getName());
           dto.setPrice(price);
           dto.setIsPhysicalCard(list.get(i).getIsPhysicalCard());
           dto.setIsPrepaymentCard(list.get(i).getIsPrepaymentCard());
           dto.setStatus(list.get(i).getStatus());
           dto.setCardDefinition(list.get(i).getCardDefinition());
           dto.setUnitOfPeriod(list.get(i).getUnitOfPeriod());
           dto.setValidPeriod(list.get(i).getValidPeriod());
           dto.setCardDefinition(list.get(i).getCardDefinition());
           packageDefinitionResultsDtolist.add(dto);
       }
       //去除门店不售卖的套餐
       for(int i=0; i<packageDefinitionResultsDtolist.size(); i++){
    	   PackageDefinitionResultsDto resultDto = packageDefinitionResultsDtolist.get(i);
    	   List<PackageDealerSelected> selectedList = mealManageService.getPackageSelected(String.valueOf(resultDto.getId()), String.valueOf(UserUtil.getCurrentUser().getDealerId()));
    	   if((selectedList == null || selectedList.isEmpty()) && resultDto.getId() != -1){
    		   packageDefinitionResultsDtolist.remove(resultDto);
    		   i--;
    	   }
       }
       return packageDefinitionResultsDtolist;
   }

@Override
public List<PackageDefinitionResultsForSelectDto> getAllPackageDefinitionListForMars(String dealerId) throws AppException {
    
    List<PackageDefinitionResultsDto> packageDefinitionResultsDtolist= new ArrayList<PackageDefinitionResultsDto>();
    //获取当前门店信息
    MasterDataDealerInfo dealerInfo = dealerDao.getDealerByDealerNum(dealerId);
    //获取套餐
    List<PackageDefinition> list=packageDefinitionDao.getAllPackageDefinitionList();
    PackageDefinitionResultsDto dto=new PackageDefinitionResultsDto();
    //默认套餐为空设置
    dto.setId(Long.valueOf("-1"));
    dto.setName(null);
    dto.setPrice(null);
    dto.setIsPhysicalCard(0);
    packageDefinitionResultsDtolist.add(dto);
    for(int i=0;i<list.size();i++){
 	   //查看套餐的适用范围,适用范围外的要删掉
 	   
 	   //构造优先级的map
        Map<String,String> priority = new HashMap<String,String>();
        List<CodeInfo> priorityList = codeMappingDao.getCodeInfoByCodeType(CouponConstants.DEALERPROPERTY);
        if(priorityList != null && !priorityList.isEmpty()){
            for(int k=0; k<priorityList.size(); k++){
                priority.put(priorityList.get(k).getCode().substring(2), priorityList.get(k).getCode());
            }
        }
        
        if(priority != null && !priority.isEmpty()){
     	   List<PackageEligibilityModel> packageEligibilityList = packageEligibilityDao.getPackageEligibilityByPackageDefId(list.get(i).getId());
     	   if(packageEligibilityList != null && !packageEligibilityList.isEmpty()){
     		   boolean isExist = false;
     		   for(int j=0; j<packageEligibilityList.size(); j++){
     			   if(priorityList != null && !priorityList.isEmpty()){
     	               for(int k=0; k<priorityList.size(); k++){
     	            	   if(priorityList.get(k).getCode().equals(packageEligibilityList.get(j).getDealerProperty())){
     	            		   String property = packageEligibilityList.get(j).getDealerProperty().substring(2);
             				   if(packageEligibilityList.get(j).getPropertyValue().equals(dealerDao.getDealersByProperty(property,dealerInfo.getDealerNum()))){
             					   isExist = true;
             				   }
             			   }
     	               }
     	           }
     			   
     		   }
     		   if(!isExist){
     			   list.remove(i);
					   i--;
					   continue;
     		   }
     	   }
        }
        //查找地方性价格
        Double price = null;
        List<TicketPriceOfDealer> ticketPriceOfDealerList = ticketPriceOfDealerDao.getTicketPriceOfDealerByDealerAndPackageDefId(Long.parseLong(dealerId),
            list.get(i).getId());
        if(ticketPriceOfDealerList != null && !ticketPriceOfDealerList.isEmpty()){
            price = ticketPriceOfDealerList.get(0).getPrice();
        }else{
            price = list.get(i).getPrice();
        }
        dto=new PackageDefinitionResultsDto();
        dto.setId(list.get(i).getId());
        dto.setName(list.get(i).getName());
        dto.setPrice(price);
        dto.setIsPhysicalCard(list.get(i).getIsPhysicalCard());
        dto.setIsPrepaymentCard(list.get(i).getIsPrepaymentCard());
        dto.setStatus(list.get(i).getStatus());
        dto.setCardDefinition(list.get(i).getCardDefinition());
        dto.setUnitOfPeriod(list.get(i).getUnitOfPeriod());
        dto.setValidPeriod(list.get(i).getValidPeriod());
        dto.setCardDefinition(list.get(i).getCardDefinition());
        dto.setSequenceNumber(list.get(i).getSequenceNumber());
        packageDefinitionResultsDtolist.add(dto);
    }
  //去除门店不售卖的套餐
    for(PackageDefinitionResultsDto resultDto : packageDefinitionResultsDtolist){
 	   List<PackageDealerSelected> selectedList = mealManageService.getPackageSelected(String.valueOf(resultDto.getId()), dealerId);
 	   if((selectedList == null || selectedList.isEmpty()) && resultDto.getId() != -1){
 		   //1:不选   0:选中
 		   resultDto.setIfChecked(0);
 	   }
    }
	List<PackageDefinitionResultsForSelectDto> resultList = new ArrayList<PackageDefinitionResultsForSelectDto>();
	//取出list中所有的cardtype
	if(packageDefinitionResultsDtolist != null && !packageDefinitionResultsDtolist.isEmpty()){
		List<String> cardTypeList = new ArrayList<String>();
		for(int i=0; i <packageDefinitionResultsDtolist.size(); i++){
			if(packageDefinitionResultsDtolist.get(i).getId() != -1){
				String cardType = packageDefinitionResultsDtolist.get(i).getCardDefinition().getName();
				cardTypeList.add(cardType);
			}
		}
		List<String> cardTypeListForDesplay = new ArrayList<String>();
		for(String card : cardTypeList){
			if(!cardTypeListForDesplay.contains(card)){
				cardTypeListForDesplay.add(card);
			}
		}
		//按照cardType来进行分类
		for(String card : cardTypeListForDesplay){
			PackageDefinitionResultsForSelectDto result = new PackageDefinitionResultsForSelectDto();
			List<PackageDefinitionResultsDto> packageDefinitionResultsDtoList = new ArrayList<PackageDefinitionResultsDto>();
			result.setCardType(card);
			for(int i=0; i<packageDefinitionResultsDtolist.size(); i++){
				if(packageDefinitionResultsDtolist.get(i).getId() != -1){
					PackageDefinitionResultsDto packageDefDto = packageDefinitionResultsDtolist.get(i);
					if(card.equals(packageDefDto.getCardDefinition().getName())){
						packageDefinitionResultsDtoList.add(packageDefDto);
					}
				}
			}
			//按照SEQUENCE_NUMBER从小至大排序
			for(int i=0; i<packageDefinitionResultsDtoList.size(); i++){
				for(int j=i; j<packageDefinitionResultsDtoList.size(); j++){
					if(packageDefinitionResultsDtoList.get(j).getSequenceNumber() < packageDefinitionResultsDtoList.get(i).getSequenceNumber()){
						PackageDefinitionResultsDto temp = new PackageDefinitionResultsDto();
						temp = packageDefinitionResultsDtoList.get(i);
						packageDefinitionResultsDtoList.set(i, packageDefinitionResultsDtoList.get(j));
						packageDefinitionResultsDtoList.set(j, temp);
					}
				}
			}
			result.setPackageDefinitionResultsDtoList(packageDefinitionResultsDtoList);
			resultList.add(result);
		}
	}
	return resultList;
}

@Override
public List<PackageDefinitionResultsForSelectDto> getAllPackageDefGroupByCardList() throws AppException {
	List<PackageDefinitionResultsDto> list = getAllPackageDefinitionList();
	List<PackageDefinitionResultsForSelectDto> resultList = new ArrayList<PackageDefinitionResultsForSelectDto>();
	//取出list中所有的cardtype
	if(list != null && !list.isEmpty()){
		List<String> cardTypeList = new ArrayList<String>();
		for(int i=0; i <list.size(); i++){
			if(list.get(i).getId() != -1){
				String cardType = list.get(i).getCardDefinition().getName();
				cardTypeList.add(cardType);
			}
		}
		HashSet<String> cardTypeSet = new HashSet<String>(cardTypeList);
		//按照cardType来进行分类
		for(String card : cardTypeSet){
			PackageDefinitionResultsForSelectDto result = new PackageDefinitionResultsForSelectDto();
			List<PackageDefinitionResultsDto> packageDefinitionResultsDtoList = new ArrayList<PackageDefinitionResultsDto>();
			result.setCardType(card);
			for(int i=0; i<list.size(); i++){
				if(list.get(i).getId() != -1){
					PackageDefinitionResultsDto packageDefDto = list.get(i);
					if(card.equals(packageDefDto.getCardDefinition().getName())){
						packageDefinitionResultsDtoList.add(packageDefDto);
					}
				}
			}
			result.setPackageDefinitionResultsDtoList(packageDefinitionResultsDtoList);
			resultList.add(result);
		}
	}
	return resultList;
}

@Override
public List<PackageDefinitionResultsForSelectDto> getAllPackageDefinitionListForSelected() throws AppException {
	List<PackageDefinitionResultsDto> packageDefinitionResultsDtolist= new ArrayList<PackageDefinitionResultsDto>();
    //获取当前门店信息
    MasterDataDealerInfo dealerInfo = dealerDao.getDealerByDealerNum(String.valueOf(UserUtil.getCurrentUser().getDealerId()));
    //获取套餐
    List<PackageDefinition> list=packageDefinitionDao.getAllPackageDefinitionList();
    PackageDefinitionResultsDto dto=new PackageDefinitionResultsDto();
    //默认套餐为空设置
    dto.setId(Long.valueOf("-1"));
    dto.setName(null);
    dto.setPrice(null);
    dto.setIsPhysicalCard(0);
    packageDefinitionResultsDtolist.add(dto);
    for(int i=0;i<list.size();i++){
 	   //查看套餐的适用范围,适用范围外的要删掉
 	   
 	   //构造优先级的map
        Map<String,String> priority = new HashMap<String,String>();
        List<CodeInfo> priorityList = codeMappingDao.getCodeInfoByCodeType(CouponConstants.DEALERPROPERTY);
        if(priorityList != null && !priorityList.isEmpty()){
            for(int k=0; k<priorityList.size(); k++){
                priority.put(priorityList.get(k).getCode().substring(2), priorityList.get(k).getCode());
            }
        }
        
        if(priority != null && !priority.isEmpty()){
     	   List<PackageEligibilityModel> packageEligibilityList = packageEligibilityDao.getPackageEligibilityByPackageDefId(list.get(i).getId());
     	   if(packageEligibilityList != null && !packageEligibilityList.isEmpty()){
     		   boolean isExist = false;
     		   for(int j=0; j<packageEligibilityList.size(); j++){
     			   if(priorityList != null && !priorityList.isEmpty()){
     	               for(int k=0; k<priorityList.size(); k++){
     	            	   if(priorityList.get(k).getCode().equals(packageEligibilityList.get(j).getDealerProperty())){
     	            		   String property = packageEligibilityList.get(j).getDealerProperty().substring(2);
             				   if(packageEligibilityList.get(j).getPropertyValue().equals(dealerDao.getDealersByProperty(property,dealerInfo.getDealerNum()))){
             					   isExist = true;
             				   }
             			   }
     	               }
     	           }
     			   
     		   }
     		   if(!isExist){
     			   list.remove(i);
					   i--;
					   continue;
     		   }
     	   }
        }
        //查找地方性价格
        Double price = null;
        List<TicketPriceOfDealer> ticketPriceOfDealerList = ticketPriceOfDealerDao.getTicketPriceOfDealerByDealerAndPackageDefId(UserUtil.getCurrentUser().getDealerId(),
            list.get(i).getId());
        if(ticketPriceOfDealerList != null && !ticketPriceOfDealerList.isEmpty()){
            price = ticketPriceOfDealerList.get(0).getPrice();
        }else{
            price = list.get(i).getPrice();
        }
        dto=new PackageDefinitionResultsDto();
        dto.setId(list.get(i).getId());
        dto.setName(list.get(i).getName());
        dto.setPrice(price);
        dto.setIsPhysicalCard(list.get(i).getIsPhysicalCard());
        dto.setIsPrepaymentCard(list.get(i).getIsPrepaymentCard());
        dto.setStatus(list.get(i).getStatus());
        dto.setCardDefinition(list.get(i).getCardDefinition());
        dto.setUnitOfPeriod(list.get(i).getUnitOfPeriod());
        dto.setValidPeriod(list.get(i).getValidPeriod());
        dto.setCardDefinition(list.get(i).getCardDefinition());
        dto.setSequenceNumber(list.get(i).getSequenceNumber());
        packageDefinitionResultsDtolist.add(dto);
    }
	//去除门店不售卖的套餐
    for(PackageDefinitionResultsDto resultDto : packageDefinitionResultsDtolist){
 	   List<PackageDealerSelected> selectedList = mealManageService.getPackageSelected(String.valueOf(resultDto.getId()), String.valueOf(UserUtil.getCurrentUser().getDealerId()));
 	   if(selectedList != null && !selectedList.isEmpty()){
 		   //0:不选  1:选中
 		   resultDto.setIfChecked(1);
 	   }
    }
	List<PackageDefinitionResultsForSelectDto> resultList = new ArrayList<PackageDefinitionResultsForSelectDto>();
	//取出list中所有的cardtype
	if(packageDefinitionResultsDtolist != null && !packageDefinitionResultsDtolist.isEmpty()){
		List<String> cardTypeList = new ArrayList<String>();
		for(int i=0; i <packageDefinitionResultsDtolist.size(); i++){
			if(packageDefinitionResultsDtolist.get(i).getId() != -1){
				String cardType = packageDefinitionResultsDtolist.get(i).getCardDefinition().getName();
				cardTypeList.add(cardType);
			}
		}
		List<String> cardTypeListForDesplay = new ArrayList<String>();
			for(String card : cardTypeList){
				if(!cardTypeListForDesplay.contains(card)){
					cardTypeListForDesplay.add(card);
				}
			}
		//按照cardType来进行分类
		for(String card : cardTypeListForDesplay){
			PackageDefinitionResultsForSelectDto result = new PackageDefinitionResultsForSelectDto();
			List<PackageDefinitionResultsDto> packageDefinitionResultsDtoList = new ArrayList<PackageDefinitionResultsDto>();
			result.setCardType(card);
			for(int i=0; i<packageDefinitionResultsDtolist.size(); i++){
				if(packageDefinitionResultsDtolist.get(i).getId() != -1){
					PackageDefinitionResultsDto packageDefDto = packageDefinitionResultsDtolist.get(i);
					if(card.equals(packageDefDto.getCardDefinition().getName())){
						packageDefinitionResultsDtoList.add(packageDefDto);
					}
				}
			}
			//按照SEQUENCE_NUMBER从小至大排序
			for(int i=0; i<packageDefinitionResultsDtoList.size(); i++){
				for(int j=i; j<packageDefinitionResultsDtoList.size(); j++){
					if(packageDefinitionResultsDtoList.get(j).getSequenceNumber() < packageDefinitionResultsDtoList.get(i).getSequenceNumber()){
						PackageDefinitionResultsDto temp = new PackageDefinitionResultsDto();
						temp = packageDefinitionResultsDtoList.get(i);
						packageDefinitionResultsDtoList.set(i, packageDefinitionResultsDtoList.get(j));
						packageDefinitionResultsDtoList.set(j, temp);
					}
				}
			}
			result.setPackageDefinitionResultsDtoList(packageDefinitionResultsDtoList);
			resultList.add(result);
		}
	}
	return resultList;
    
}

}
